package actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import document.AwesomeDocument;

import misc.Vals;

import textArea.AwesomeTextPanel;
import frame.AwesomeFrame;

/**
 * Creates the visual interface for saving a file.
 * @author Brittin
 *
 */
public class SaveFileAction extends AwesomeMenuAction {

	public SaveFileAction(String name, String desc) {
		super(name, desc);
		putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_S));
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		AwesomeTextPanel panel = this.getSelectedTextPanel(e);
		AwesomeFrame frame = this.getParentFrame(e);
		AwesomeDocument doc = panel.getDocumentType();
		
		if (doc == null)
			return;
		
		// If the current document is new it needs a name
		if (frame.getCurrentFile() == null) {
			JFileChooser fc = this.getFileChooser(e);
			
			// restrict file filter to current extension
//			fc.setAcceptAllFileFilterUsed( false );
//			fc.addChoosableFileFilter(new FileNameExtensionFilter( doc.getLabel(), doc.getExtension() ) );
//			if (fc == null)
//				return;
			int retVal = fc.showSaveDialog(this.getParentFrame(e));
			//fc.setAcceptAllFileFilterUsed( true );
			if (retVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				try {
					ActionFileIO.saveFile(file, panel.getTextPane().getText());
				} catch (IOException ex) {
					JOptionPane.showMessageDialog(null,
							Vals.fileWriteErrorMessage);
				}
				frame.setCurrentFile(file);
				frame.setTitle(Vals.mainFrameTitle + ": " + file.getName().substring(0, file.getName().lastIndexOf('.')));
			}
			// Otherwise it isnt new
		} else {
			File file = frame.getCurrentFile();
			try {
				ActionFileIO.saveFile(file, panel.getTextPane().getText());
			} catch (IOException ex) {
				JOptionPane.showMessageDialog(null,
						Vals.fileWriteErrorMessage);
			}
		}
		
	}
}
